package com.aes;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;


/**
 * Created by lenovo on 2016/1/7.
 */
public class ImoocAES {
    private static String src = "imooc security aes";

    public static void main(String[] args){
        jdkAES();
    }

    public static void jdkAES(){
        try {
            //生成KEY
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(new SecureRandom());//128
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] bytes = secretKey.getEncoded();

            //转换KEY
            Key key = new SecretKeySpec(bytes,"AES");

            //加密
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE,key);
            byte[] bytes1 = cipher.doFinal(src.getBytes());
            System.out.println("jdk aes encrypt : "+ Base64.encodeBase64String(bytes1));

            //解密
            cipher.init(Cipher.DECRYPT_MODE,key);
            bytes1 = cipher.doFinal(bytes1);
            System.out.println("jdk aes desrypt : " +new String(bytes1));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
